import time

import network


# ------------------- WiFi连接 -------------------
def connect_wifi(ssid, pwd):
    wlan = network.WLAN(network.STA_IF)  # 启动STA模式（客户端模式）
    wlan.active(True)

    if not wlan.isconnected():
        print(f"连接WiFi: {ssid}...")
        wlan.connect(ssid, pwd)

        # 等待连接（超时10秒）
        timeout = 10
        while not wlan.isconnected() and timeout > 0:
            time.sleep(1)
            timeout -= 1

        if not wlan.isconnected():
            print("WiFi连接失败！")
            return False
        else:
            print(f"WiFi已连接，IP: {wlan.ifconfig()[0]}")
            return True
    else:
        print("WiFi已连接")
        return True
